package com.zxl.admin.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zxl.common.constant.member.MemberTypeConstant;
import com.zxl.common.exception.BusinessException;
import com.zxl.common.mapper.SysMchMapper;
import com.zxl.common.mapper.SysMemberMapper;
import com.zxl.common.mapper.SysShopMapper;
import com.zxl.common.model.bo.shop.ShopAdd;
import com.zxl.common.model.pojo.SysMch;
import com.zxl.common.model.pojo.SysMember;
import com.zxl.common.model.pojo.SysShop;
import com.zxl.common.service.SysMchService;
import com.zxl.common.service.SysShopService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author zxw
 * @date 2023/5/10
 */
@Service
public class ShopService {
    @Resource
    private SysShopMapper sysShopMapper;
    @Resource
    private SysMchMapper sysMchMapper;
    @Resource
    private SysMemberMapper sysMemberMapper;

    @Transactional(rollbackFor = Exception.class)
    public void add(ShopAdd shopAdd) {
        Integer memberId = shopAdd.getMemberId();
        if (memberId != null){
            this.valid(memberId);
            SysMch mch = new SysMch();
            mch.setMemberId(memberId);
            sysMchMapper.insert(mch);
            sysMemberMapper.update(null, new UpdateWrapper<SysMember>()
                    .eq("type", MemberTypeConstant.MEMBER_TYPE_SHOP.getCode()));
            shopAdd.setMchId(mch.getId());
        }
        SysShop sysShop = new SysShop();
        BeanUtil.copyProperties(shopAdd, sysShop);
        sysShopMapper.insert(sysShop);
    }


    private void valid(Integer memberId){
        SysMch sysMch = sysMchMapper.selectOne(new QueryWrapper<SysMch>()
                .eq("member_id", memberId));
        if (sysMch != null){
            throw new BusinessException("该用户已经是商户店主");
        }

    }
}
